#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
清理临时文件工具 (Cleanup Tool)

功能：
1. 清空 99_工作空间/ 下所有临时文件
2. 清空 01_信息与灵感/00_收件箱/ 中所有临时数据
3. 保留所有 README.md 文件
4. 保留所有 .gitkeep 文件

使用方法：
    python cleanup.py

作者：思考框架
版本：1.0
创建时间：2025-10-29
"""

import os
import shutil
from datetime import datetime

# ANSI颜色代码
class Color:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    END = '\033[0m'
    BOLD = '\033[1m'

def print_header():
    """打印程序标题"""
    print()
    print(f"{Color.BOLD}{Color.CYAN}{'=' * 70}{Color.END}")
    print(f"{Color.BOLD}{Color.CYAN}🧹 思考框架 - 临时文件清理工具{Color.END}")
    print(f"{Color.BOLD}{Color.CYAN}{'=' * 70}{Color.END}")
    print()

def print_section(title):
    """打印章节标题"""
    print()
    print(f"{Color.BOLD}{Color.BLUE}【{title}】{Color.END}")
    print()

def should_keep_file(filename):
    """判断文件是否应该保留"""
    keep_files = {
        'README.md',
        '.gitkeep',
        '.gitignore'
    }
    return filename in keep_files

def scan_directory(path):
    """扫描目录，统计文件数量"""
    total_files = 0
    total_dirs = 0
    keep_files = 0
    delete_files = 0
    
    files_to_delete = []
    dirs_to_delete = []
    
    if not os.path.exists(path):
        return None
    
    # 遍历目录
    for root, dirs, files in os.walk(path, topdown=False):
        # 统计文件
        for filename in files:
            total_files += 1
            if should_keep_file(filename):
                keep_files += 1
            else:
                delete_files += 1
                file_path = os.path.join(root, filename)
                files_to_delete.append(file_path)
        
        # 统计空目录（除了根目录）
        for dirname in dirs:
            total_dirs += 1
            dir_path = os.path.join(root, dirname)
            # 检查目录是否为空（或只包含应保留的文件）
            if os.path.exists(dir_path):
                contents = os.listdir(dir_path)
                # 过滤掉应保留的文件
                non_keep_contents = [c for c in contents if not should_keep_file(c)]
                if len(non_keep_contents) == 0 and len(contents) > 0:
                    # 目录只包含应保留的文件
                    pass
                elif len(contents) == 0:
                    # 完全空的目录
                    dirs_to_delete.append(dir_path)
    
    return {
        'total_files': total_files,
        'total_dirs': total_dirs,
        'keep_files': keep_files,
        'delete_files': delete_files,
        'files_to_delete': files_to_delete,
        'dirs_to_delete': dirs_to_delete
    }

def format_size(size):
    """格式化文件大小"""
    for unit in ['B', 'KB', 'MB', 'GB']:
        if size < 1024.0:
            return f"{size:.2f} {unit}"
        size /= 1024.0
    return f"{size:.2f} TB"

def get_file_size(file_path):
    """获取文件大小"""
    try:
        return os.path.getsize(file_path)
    except:
        return 0

def clean_directory(path, stats):
    """清理目录"""
    deleted_files = 0
    deleted_dirs = 0
    deleted_size = 0
    errors = []
    
    # 删除文件
    for file_path in stats['files_to_delete']:
        try:
            size = get_file_size(file_path)
            os.remove(file_path)
            deleted_files += 1
            deleted_size += size
            rel_path = os.path.relpath(file_path, '.')
            print(f"  {Color.GREEN}✅{Color.END} 已删除：{rel_path}")
        except Exception as e:
            errors.append((file_path, str(e)))
            print(f"  {Color.RED}❌{Color.END} 删除失败：{file_path} - {e}")
    
    # 删除空目录
    for dir_path in stats['dirs_to_delete']:
        try:
            os.rmdir(dir_path)
            deleted_dirs += 1
            rel_path = os.path.relpath(dir_path, '.')
            print(f"  {Color.GREEN}✅{Color.END} 已删除空目录：{rel_path}")
        except Exception as e:
            # 忽略目录非空的错误（可能有其他进程在使用）
            pass
    
    return deleted_files, deleted_dirs, deleted_size, errors

def main():
    """主函数"""
    print_header()
    
    # 定义要清理的目录
    targets = [
        {
            'path': '99_工作空间',
            'name': 'AI工作空间',
            'desc': '临时方案、分析、建议、报告、脚本'
        },
        {
            'path': '01_信息与灵感/00_收件箱',
            'name': '信息收件箱',
            'desc': '临时导入的网页、文档、资料'
        }
    ]
    
    # 扫描阶段
    print_section("1. 扫描目标目录")
    
    all_stats = {}
    total_delete_files = 0
    total_delete_size = 0
    
    for target in targets:
        path = target['path']
        name = target['name']
        
        print(f"📂 {Color.BOLD}{name}{Color.END} ({path})")
        
        if not os.path.exists(path):
            print(f"  {Color.YELLOW}⚠️  目录不存在{Color.END}")
            continue
        
        stats = scan_directory(path)
        if stats:
            all_stats[path] = stats
            
            # 计算要删除的文件总大小
            delete_size = sum(get_file_size(f) for f in stats['files_to_delete'])
            total_delete_size += delete_size
            total_delete_files += stats['delete_files']
            
            print(f"  总文件：{stats['total_files']}个")
            print(f"  保留文件：{Color.GREEN}{stats['keep_files']}个{Color.END} (README.md等)")
            print(f"  {Color.RED}待删除文件：{stats['delete_files']}个{Color.END}")
            print(f"  {Color.RED}占用空间：{format_size(delete_size)}{Color.END}")
            if stats['dirs_to_delete']:
                print(f"  空目录：{len(stats['dirs_to_delete'])}个")
        
        print()
    
    # 如果没有要删除的文件
    if total_delete_files == 0:
        print(f"{Color.GREEN}✅ 所有目录都是干净的，无需清理！{Color.END}")
        print()
        return
    
    # 确认阶段
    print_section("2. 确认清理操作")
    
    print(f"⚠️  {Color.BOLD}{Color.YELLOW}即将删除：{Color.END}")
    print(f"   - 文件数量：{Color.RED}{total_delete_files}个{Color.END}")
    print(f"   - 占用空间：{Color.RED}{format_size(total_delete_size)}{Color.END}")
    print()
    print(f"✅ {Color.GREEN}将保留所有 README.md 文件{Color.END}")
    print()
    
    # 用户确认
    while True:
        response = input(f"{Color.BOLD}确认删除？(yes/no): {Color.END}").strip().lower()
        if response in ['yes', 'y']:
            break
        elif response in ['no', 'n']:
            print()
            print(f"{Color.YELLOW}❌ 已取消清理操作{Color.END}")
            print()
            return
        else:
            print(f"{Color.RED}请输入 yes 或 no{Color.END}")
    
    # 清理阶段
    print_section("3. 执行清理")
    
    total_deleted_files = 0
    total_deleted_dirs = 0
    total_deleted_size = 0
    all_errors = []
    
    for target in targets:
        path = target['path']
        name = target['name']
        
        if path not in all_stats:
            continue
        
        print(f"📂 {Color.BOLD}清理 {name}{Color.END}")
        print()
        
        stats = all_stats[path]
        deleted_files, deleted_dirs, deleted_size, errors = clean_directory(path, stats)
        
        total_deleted_files += deleted_files
        total_deleted_dirs += deleted_dirs
        total_deleted_size += deleted_size
        all_errors.extend(errors)
        
        print()
    
    # 结果报告
    print_section("4. 清理完成")
    
    print(f"✅ {Color.GREEN}成功删除：{Color.END}")
    print(f"   - 文件：{total_deleted_files}个")
    if total_deleted_dirs > 0:
        print(f"   - 空目录：{total_deleted_dirs}个")
    print(f"   - 释放空间：{format_size(total_deleted_size)}")
    print()
    
    if all_errors:
        print(f"❌ {Color.RED}失败：{len(all_errors)}个{Color.END}")
        for file_path, error in all_errors[:5]:  # 只显示前5个错误
            print(f"   - {file_path}: {error}")
        if len(all_errors) > 5:
            print(f"   ... 还有{len(all_errors) - 5}个错误")
        print()
    
    # 生成清理日志
    log_dir = '99_工作空间/03_报告库'
    if os.path.exists(log_dir):
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        log_file = os.path.join(log_dir, f'清理日志_{timestamp}.md')
        
        try:
            with open(log_file, 'w', encoding='utf-8') as f:
                f.write(f"# 临时文件清理日志\n\n")
                f.write(f"**清理时间：** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
                f.write(f"---\n\n")
                f.write(f"## 清理结果\n\n")
                f.write(f"- ✅ 成功删除文件：{total_deleted_files}个\n")
                if total_deleted_dirs > 0:
                    f.write(f"- ✅ 成功删除空目录：{total_deleted_dirs}个\n")
                f.write(f"- ✅ 释放空间：{format_size(total_deleted_size)}\n")
                if all_errors:
                    f.write(f"- ❌ 失败：{len(all_errors)}个\n")
                f.write(f"\n---\n\n")
                f.write(f"## 清理目标\n\n")
                for target in targets:
                    if target['path'] in all_stats:
                        f.write(f"### {target['name']}\n\n")
                        f.write(f"- 路径：`{target['path']}`\n")
                        f.write(f"- 说明：{target['desc']}\n")
                        stats = all_stats[target['path']]
                        f.write(f"- 删除文件：{stats['delete_files']}个\n")
                        f.write(f"\n")
            
            print(f"📄 清理日志已保存：{log_file}")
            print()
        except Exception as e:
            print(f"{Color.YELLOW}⚠️  日志保存失败：{e}{Color.END}")
            print()
    
    print(f"{Color.BOLD}{Color.GREEN}🎉 清理完成！思考框架已整洁！{Color.END}")
    print()
    print(f"{Color.CYAN}{'=' * 70}{Color.END}")
    print()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print()
        print()
        print(f"{Color.YELLOW}❌ 已取消清理操作{Color.END}")
        print()
    except Exception as e:
        print()
        print(f"{Color.RED}❌ 发生错误：{e}{Color.END}")
        print()
        import traceback
        traceback.print_exc()

